from typing import Annotated, List, Optional
from langgraph.graph import MessagesState
from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
from datetime import datetime
from enum import Enum


class UserIntent(Enum):
    COURSE_INQUIRY = "course_inquiry"
    ENROLLMENT = "enrollment"
    PROGRESS_CHECK = "progress_check"
    TECHNICAL_SUPPORT = "technical_support"
    BILLING = "billing"


class CourseDifficulty(Enum):
    BEGINNER = "beginner"
    INTERMEDIATE = "intermediate"
    ADVANCED = "advanced"


# 复杂的业务状态定义
class EducationSupportState(MessagesState):
    # 用户基本信息
    user_id: str
    user_name: str
    email: str
    phone: str

    # 用户意图和上下文
    current_intent: UserIntent
    conversation_stage: str  # "greeting" -> "info_gathering" -> "processing" -> "confirmation" -> "closing"

    # 课程相关信息
    course_id: Optional[str]
    course_name: Optional[str]
    course_difficulty: Optional[CourseDifficulty]
    course_price: Optional[float]

    # 报名信息
    enrollment_status: str  # "not_started" -> "in_progress" -> "completed" -> "confirmed"
    payment_status: str  # "unpaid" -> "processing" -> "paid" -> "confirmed"
    enrollment_id: Optional[str]

    # 学习进度
    current_lesson: Optional[str]
    progress_percentage: int
    last_accessed_date: Optional[datetime]

    # 技术支持信息
    technical_issue: Optional[str]
    support_ticket_id: Optional[str]

    # 需要人工审核的标志
    needs_human_review: bool
    review_reason: Optional[str]

    # 系统状态
    session_start_time: datetime
    last_activity_time: datetime
    interaction_count: int


# 智能客服节点函数
def intent_classifier(state: EducationSupportState):
    """识别用户意图"""
    messages = state['messages']
    last_message = messages[-1].content if messages else ""

    # 根据用户消息内容判断意图
    if any(keyword in last_message.lower() for keyword in ["课程", "学习", "python", "编程"]):
        intent = UserIntent.COURSE_INQUIRY
    elif any(keyword in last_message.lower() for keyword in ["报名", "注册", " enroll"]):
        intent = UserIntent.ENROLLMENT
    elif any(keyword in last_message.lower() for keyword in ["进度", "学到哪", "完成"]):
        intent = UserIntent.PROGRESS_CHECK
    elif any(keyword in last_message.lower() for keyword in ["不能", "无法", "错误", "bug"]):
        intent = UserIntent.TECHNICAL_SUPPORT
    elif any(keyword in last_message.lower() for keyword in ["价格", "费用", "付款", "支付"]):
        intent = UserIntent.BILLING
    else:
        intent = UserIntent.COURSE_INQUIRY

    return {
        "current_intent": intent,
        "conversation_stage": "intent_identified",
        "interaction_count": state.get("interaction_count", 0) + 1
    }


def course_recommender(state: EducationSupportState):
    """根据用户需求推荐课程"""
    # 模拟根据用户意图推荐课程
    if state["current_intent"] == UserIntent.COURSE_INQUIRY:
        return {
            "course_id": "PY101",
            "course_name": "Python编程入门",
            "course_difficulty": CourseDifficulty.BEGINNER,
            "course_price": 299.0,
            "conversation_stage": "course_recommended"
        }
    elif state["current_intent"] == UserIntent.ENROLLMENT:
        return {
            "conversation_stage": "enrollment_started"
        }
    return {}


def enrollment_processor(state: EducationSupportState):
    """处理报名流程"""
    if state["conversation_stage"] == "enrollment_started":
        # 模拟收集用户信息
        required_fields = ["user_name", "email", "phone"]
        missing_fields = [field for field in required_fields if not state.get(field)]

        if missing_fields:
            return {
                "conversation_stage": "info_gathering",
                "needs_human_review": len(missing_fields) > 2,  # 如果缺少太多信息需要人工介入
                "review_reason": f"缺少必要信息: {', '.join(missing_fields)}" if missing_fields else None
            }
        else:
            # 所有信息齐全，可以创建报名
            return {
                "enrollment_status": "in_progress",
                "payment_status": "processing",
                "enrollment_id": f"ENROLL_{state['user_id']}_{int(datetime.now().timestamp())}",
                "conversation_stage": "payment_processing"
            }
    return {}


def human_review_handler(state: EducationSupportState):
    """处理需要人工审核的情况"""
    if state.get("needs_human_review", False):
        # 这里可以暂停工作流等待人工审核
        # 为了演示，我们模拟人工审核完成
        return {
            "needs_human_review": False,
            "review_reason": None,
            "conversation_stage": "human_review_completed"
        }
    return {}


def payment_processor(state: EducationSupportState):
    """处理支付流程"""
    if state.get("payment_status") == "processing":
        # 模拟支付处理
        return {
            "payment_status": "paid",
            "enrollment_status": "completed",
            "conversation_stage": "enrollment_confirmed"
        }
    return {}


def response_generator(state: EducationSupportState):
    """生成最终响应"""
    if state["conversation_stage"] == "enrollment_confirmed":
        return {
            "messages": [AIMessage(content=f"恭喜 {state.get('user_name', '用户')}！您已成功报名 {state.get('course_name', '课程')}。欢迎开始学习之旅！")],
            "conversation_stage": "closing"
        }
    elif state["conversation_stage"] == "course_recommended":
        return {
            "messages": [AIMessage(content=f"根据您的需求，我推荐 {state.get('course_name')} 课程。这是一门 {state.get('course_difficulty', '入门').value} 级别的课程，价格为 {state.get('course_price', 0)} 元。您是否感兴趣？")],
            "conversation_stage": "recommendation_sent"
        }
    return {}


# 构建复杂的工作流
def create_education_support_workflow():
    from langgraph.graph import StateGraph
    from langgraph.checkpoint.memory import MemorySaver

    workflow = StateGraph(EducationSupportState)

    # 添加节点
    workflow.add_node("intent_classifier", intent_classifier)
    workflow.add_node("course_recommender", course_recommender)
    workflow.add_node("enrollment_processor", enrollment_processor)
    workflow.add_node("human_review_handler", human_review_handler)
    workflow.add_node("payment_processor", payment_processor)
    workflow.add_node("response_generator", response_generator)

    # 设置流程
    workflow.set_entry_point("intent_classifier")
    workflow.add_edge("intent_classifier", "course_recommender")
    workflow.add_edge("course_recommender", "enrollment_processor")
    workflow.add_edge("enrollment_processor", "human_review_handler")
    workflow.add_edge("human_review_handler", "payment_processor")
    workflow.add_edge("payment_processor", "response_generator")

    # 编译工作流
    checkpointer = MemorySaver()
    app = workflow.compile(checkpointer=checkpointer)

    return app


# 使用示例
def demo_education_support():
    app = create_education_support_workflow()

    # 模拟用户对话
    config = {"configurable": {"thread_id": "user_12345"}}

    # 初始状态 - 用户第一次咨询
    initial_messages = [
        HumanMessage(content="你好，我想了解一下Python编程课程")
    ]

    print("=== 教育平台智能客服演示 ===\n")

    # 第一轮对话
    print("1. 用户首次咨询:")
    print(f"用户: {initial_messages[0].content}")

    result = app.invoke({"messages": initial_messages}, config)
    if result.get("messages"):
        print(f"客服: {result['messages'][-1].content}")

    # 查看当前状态
    current_state = app.get_state(config)
    print(f"\n当前状态 - 意图: {current_state.values.get('current_intent')}")
    print(f"对话阶段: {current_state.values.get('conversation_stage')}")
    print(f"推荐课程: {current_state.values.get('course_name')}")

    # 第二轮对话 - 用户决定报名
    print("\n" + "-" * 50)
    print("2. 用户决定报名:")
    enrollment_message = [HumanMessage(content="我想报名Python编程入门课程")]

    # 手动更新用户信息（模拟用户已登录）
    app.update_state(config, {
        "user_id": "USER12345",
        "user_name": "张三",
        "email": "zhangsan@example.com",
        "phone": "13800138000"
    })

    print(f"用户: {enrollment_message[0].content}")
    result = app.invoke({"messages": enrollment_message}, config)

    if result.get("messages"):
        print(f"客服: {result['messages'][-1].content}")

    # 查看最终状态
    final_state = app.get_state(config)
    print(f"\n最终状态:")
    print(f"  用户ID: {final_state.values.get('user_id')}")
    print(f"  用户名: {final_state.values.get('user_name')}")
    print(f"  报名状态: {final_state.values.get('enrollment_status')}")
    print(f"  支付状态: {final_state.values.get('payment_status')}")
    print(f"  报名ID: {final_state.values.get('enrollment_id')}")


# 运行演示
if __name__ == "__main__":
    demo_education_support()
